﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CodeDynamiksEngine;

using MESCodeFile;

namespace mes_tublay
{
    public partial class frmBPLSFeesAndChargesManager : Form
    {
        CodeScript script;
        CodeProcessor proc = new CodeProcessor(ThreadingMode.Normal);
        DataCache dat = new DataCache("myData");
        DataCache cache = new DataCache("myData");
        updateInfo feeInfo = new updateInfo();

        int userToEdit = -1;
        bool isEditingMode = false;

        public frmBPLSFeesAndChargesManager()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
            btnCommit.Click += new EventHandler(btnCommit_Click);
            grdFeesAndCharges.DoubleClick += new EventHandler(grdFeesAndCharges_DoubleClick);
        }

        void grdFeesAndCharges_DoubleClick(object sender, EventArgs e)
        {
            //When the user double clicks the user profile, load the profile
            if (grdFeesAndCharges.SelectedRows.Count == 0) return;
            dat.SetActivePage(0);
            userToEdit = grdFeesAndCharges.SelectedRows[0].Index;
            LoadFeesAndChargesData();
        }

        void btnCommit_Click(object sender, EventArgs e)
        {
            if (txtCode.Text != "" && txtResponsibleOffice.Text != "" && txtTypeOfServices.Text != "")
            {
                if (isEditingMode)
                {
                    Confirm.Question("Save Information", "Please double check your entries before saving.\r\n" +
                   "Do you wish to continue saving?");
                    saveInformation();
                }
                else
                {
                    if (!DuplicateService())
                    {
                        Confirm.Question("Save Information", "Please double check your entries before saving.\r\n" +
                        "Do you wish to continue saving?");
                                saveInformation();
                    }
                    else
                    {
                        Confirm.Error("Duplicate Data", "Already Exist");
                    }
                }
            }
        }

        void proc_ProcessCompleted(object sender, EventArgs e)
        {
            proc.SafeCall(this, delegate
            {
                if (proc.State == ProcessorFlag.Error ||
                    proc.State == ProcessorFlag.DataRdyErr ||
                    proc.State == ProcessorFlag.ReadyErr)
                {
                    MessageBox.Show(proc.GetProcessorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    proc.ClearErrorFlag();
                    return;
                }
                switch (proc.GetLastProcessName().ToString())
                {
                    case "SAVE":
                    case "LOAD":
                        proc.DataFetch(out dat);
                        //Set the active page before exporting
                        if (dat.GetPageSize() >= 1)
                        {
                            dat.SetActivePage(1);
                            grdFeesAndCharges.DataSource = dat.ExportPage();
                            grdFeesAndCharges.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                            grdFeesAndCharges.Columns[3].DefaultCellStyle.Format = "#,#0.00";

                            dat.SetActivePage(2);
                            if (!txtResponsibleOffice.Focused)
                            {
                                txtResponsibleOffice.Items.Clear();
                                txtResponsibleOffice.Items.AddRange(dat.GetStringList(0));
                            }
                        }

                        //clear fields
                        txtCode.Text = "";
                        txtFee.Value = 0;
                        txtTypeOfServices.Text = "";
                        txtCode.Focus();
                        break;
                    case "GETAPPDATA":
                        proc.DataFetch(out cache);
                        cache.SetActivePage(0);
                         //check if there is existing record on the tableDocumentsCheckList
                        if (cache.GetRecordCount(0) == 1)
                        {
                            isEditingMode = true;
                            txtResponsibleOffice.Text = cache.GetValue(0, "fDepartment").ToString();
                            txtCode.Text = cache.GetValue(0, "fCode").ToString();
                            txtTypeOfServices.Text = cache.GetValue(0, "fTypeOfService").ToString();
                            txtFee.Value = decimal.Parse(cache.GetValue(0, "fFee").ToString());
                        }
                        feeInfo.fID = cache.GetValue(0, "fID").ToString();
                        feeInfo.fStamp = DateTime.Parse(cache.GetValue(0, "fStamp").ToString());
                        break;
                    default:
                        break;
                }
            }); 
        }
        
        private void InitializeForm()
        {
            proc.ProcessCompleted += new EventHandler(proc_ProcessCompleted);
            loadingInfo();
        }
        //load information
        void loadingInfo()
        {
            CodeScript s = new CodeScript("LOAD");
            s.Add(CodeIns.DBU_NEW_CORE);
            s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                    Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));
            s.Add(CodeIns.DBU_BEGIN_TRANSACTION);

            s.Add(CodeIns.DBU_QUERY, "SELECT * FROM tbldeptotherfeescharges ORDER BY fDepartment ASC, fTypeOfService ASC");
            s.Add(CodeIns.DBU_QUERY, "SELECT fDepartment AS 'Department', fCode AS 'Code', fTypeOfService AS 'Type of Service', fFee AS 'Charge Amount' FROM tbldeptotherfeescharges ORDER BY fDepartment ASC, fTypeOfService ASC");
            s.Add(CodeIns.DBU_QUERY, "SELECT fData FROM tbllookup WHERE fKey = 'PRIVILEGE'");
            s.Add(CodeIns.DBU_END);
            proc.Run(s);
        }
        //check duplicate service entry
        bool DuplicateService()
        {
            bool isExist = false;
            for (int i = 0; i < grdFeesAndCharges.Rows.Count; i++)
            {
                if (txtTypeOfServices.Text.Equals(grdFeesAndCharges.Rows[i].Cells[2].Value.ToString()) && txtResponsibleOffice.Text.Equals(grdFeesAndCharges.Rows[i].Cells[0].Value.ToString()))
                {
                    isExist = true;
                    i = grdFeesAndCharges.Rows.Count;
                }
            }
            return isExist;
        }
        //save info from the database
        void saveInformation()
        {
            CodeScript s = new CodeScript("SAVE");
            s.Add(CodeIns.DBU_NEW_CORE);
            s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                    Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));
            s.Add(CodeIns.DBU_BEGIN_TRANSACTION);
            if (!isEditingMode)
            {
                s.Add(CodeIns.DBU_INSERT, "tbldeptotherfeescharges", new string[] { "fDepartment", "fCode", "fTypeOfService", "fFee" },
                    new object[] { "'" + txtResponsibleOffice.Text + "'", "'" + txtCode.Text.Trim() + "'", "'" + txtTypeOfServices.Text.Trim() + "'", "'" + double.Parse(txtFee.Value.ToString()).ToString() + "'" });
            }
            else
            {
                s.Add(CodeIns.DBU_UPDATE, "tbldeptotherfeescharges", new string[] { "fDepartment", "fCode", "fTypeOfService", "fFee" },
                    new object[] { "'" + txtResponsibleOffice.Text + "'", "'" + txtCode.Text.Trim() + "'", "'" + txtTypeOfServices.Text.Trim() + "'", "'" + double.Parse(txtFee.Value.ToString()).ToString() + "'" }, "fID='" + feeInfo.fID + "' AND fStamp='" + Helper.ToMySQLDateTime(feeInfo.fStamp) + "'");
            }
            s.Add(CodeIns.DBU_QUERY, "SELECT * FROM tbldeptotherfeescharges ORDER BY fDepartment ASC, fTypeOfService ASC");
            s.Add(CodeIns.DBU_QUERY, "SELECT fDepartment AS 'Department', fCode AS 'Code', fTypeOfService AS 'Type of Service', fFee AS 'Charge Amount' FROM tbldeptotherfeescharges ORDER BY fDepartment ASC, fTypeOfService ASC");
            s.Add(CodeIns.DBU_QUERY, "SELECT fData FROM tbllookup WHERE fKey = 'PRIVILEGE'");
            s.Add(CodeIns.DBU_END);
            proc.Run(s);
        }
        //load fees and charges
        void LoadFeesAndChargesData()
        {
            CodeScript s = new CodeScript("GETAPPDATA");
            s.Add(CodeIns.SYS_USE_CORE, 0);
            s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                    Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));

            s.Add(CodeIns.DBU_QUERY, "SELECT * FROM tbldeptotherfeescharges WHERE fTypeOfService=" + Sym.PQS(dat.GetValue(userToEdit, "fTypeOfService").ToString()) + " AND fDepartment = '" + dat.GetValue(userToEdit, "fDepartment").ToString() + "'");
            s.Add(CodeIns.DBU_END);

            proc.Run(s);
        }
    }
}
